﻿using BasicInformation.ApiRead.Application.Command.Depot;
using BasicInformation.Domain;
using BasicInformation.Dtos;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using BasicInformation.Infrastructure.Interface;
using Dapper;
using MediatR;
using MySqlX.XDevAPI.Common;
using System.Text;

namespace BasicInformation.ApiRead.Application.Handler.Depot
{
    /// <summary>
    /// 显示查询分页处理类
    /// </summary>
    public class GetDepotHandler : IRequestHandler<GetDepotCommand, ApiPaging<DepotDTO>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<GetDepotHandler> logger;

        public GetDepotHandler(DatabaseContext db,ILogger<GetDepotHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiPaging<DepotDTO>> Handle(GetDepotCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<DepotDTO> paging = new ApiPaging<DepotDTO>();
            StringBuilder sql = new StringBuilder();
            StringBuilder countSql = new StringBuilder();

            // 主查询SQL
            // 主查询SQL
            sql.Append(@"SELECT
	                    d.DepotId,
	                        d.DepotCode,
	                        d.DepotName,
	                        d.LeaseTime,
	                        dt.DTypeId,
	                        dt.DTypeName,
	                        dept.Department_Id,
	                        dept.Department_Name,
	                        d.IsState,
	                        d.IsPreset,
	                        d.DepotAddr,
	                        d.DepotArea,
	                        d.Contact,
	                        d.Tel 
                        FROM
	                        depotmodel d
	                        JOIN depottypemodel dt ON d.DTypeId = dt.DTypeId
	                        LEFT JOIN departments dept ON d.Department_Id = dept.Department_Id
                        WHERE
	                        d.IsDel = 0");

            // 计数SQL - 包含相同条件
            countSql.Append(@"SELECT COUNT(*) 
                    FROM depotmodel d
                    WHERE d.IsDel = 0");

            // 添加查询条件
            if (!string.IsNullOrEmpty(request.DepotCode))
            {
                sql.Append(" AND d.DepotCode = @DepotCode");
                countSql.Append(" AND d.DepotCode = @DepotCode");
            }
            if (!string.IsNullOrEmpty(request.DepotName))
            {
                sql.Append(" AND d.DepotName LIKE @DepotName");
                countSql.Append(" AND d.DepotName LIKE @DepotName");
            }
            if (request.DTypeId > 0)
            {
                sql.Append(" AND d.DTypeId = @DTypeId");
                countSql.Append(" AND d.DTypeId = @DTypeId");
            }
            if (request.Department_Id > 0)
            {
                sql.Append(" AND d.Department_Id = @Department_Id");
                countSql.Append(" AND d.Department_Id = @Department_Id");
            }

            // 添加排序和分页
            sql.Append(" ORDER BY d.DepotId ASC LIMIT @size OFFSET @offset");

            // 设置参数
            var parameters = new
            {
                DepotCode = request.DepotCode,
                DepotName = string.IsNullOrEmpty(request.DepotName) ? null : $"%{request.DepotName}%",
                DTypeId = request.DTypeId,
                Department_Id = request.Department_Id,
                offset = (request.index - 1) * request.size,
                size = request.size
            };

            try
            {
                // 执行查询
                var pageData = await db.DapperConnection.QueryAsync<DepotDTO>(sql.ToString(), parameters);

                // 执行计数查询 - 使用countSql和相同参数
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.size);

                // 设置返回结果
                paging.Msg = "仓库管理查询成功";
                paging.Code = ApiEnum.OK;
                paging.Data = pageData.ToList();
                paging.TotalCount = totalCount;
                paging.TotalPCount = totalPage;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "仓库管理查询失败");
                paging.Code = ApiEnum.Fail;
                paging.Msg = "仓库管理查询失败";
            }

            return paging;
        }
    }
}
